Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
How can i apply style only to the clicked element [React]

I'm trying to apply conditional styles in React. I need to apply an animation when use click on delete button but this is applied to every element from the array

Component

import React, { useState } from 'react';

import './styles.css';

const Element = () => {
  const [onDelete, setOnDelete] = useState(false);
  const list = [
    {
      name: 'Jhon',
      age: '20',
    },
    {
      name: 'Maria',
      age: '25',
    },
  ];

  return (
    <>
      {list.map((item) => (
        <ul className={onDelete ? 'onDelete-apply' : ''}>
          <li>{item.name}</li>
          <li>{item.age}</li>
          <button onClick={() => setOnDelete(true)}>
            Delete
          </button>
        </ul>
      ))}
    </>
  );
};

export default Element;

Styles

.onDelete-apply {
  background-color: red;
}

*For example in this component i want to apply red background only to the clicked element *

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should be traking the element that it is clicked by its index, insted of true or false, on click you set the index of the clicked item in the state and then check if that index is the same as the index of the element when rendered

import React, { useState } from 'react';

import './styles.css';

const Element = () => {
const [deletedIndex, setDeletedIndex] = useState(false);
      const list = [
        {
          name: 'Jhon',
          age: '20',
        },
        {
          name: 'Maria',
          age: '25',
        },
      ];
    
      return (
        <>
          {list.map((item, i) => (
            <ul key={i} className={deletedIndex === i ? 'onDelete-apply' : ''}>
              <li>{item.name}</li>
              <li>{item.age}</li>
              <button onClick={() => setDeletedIndex(i)}>Delete</button>
            </ul>
          ))}
        </>
      );
export default Element;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda